//package com.geek.water.controller;
//
//import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
//import com.geek.water.constant.CodeConstant;
//import com.geek.water.constant.MessageConstant;
//import com.geek.water.entity.Area;
//import com.geek.water.entity.Site;
//import com.geek.water.exception.WaterException;
//import com.geek.water.result.Result;
//import com.geek.water.service.AreaService;
//import com.geek.water.service.SiteService;
//import com.geek.water.vo.AreaTreeVO;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import lombok.RequiredArgsConstructor;
//import org.springframework.web.bind.annotation.*;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
///**
// * @author yangwenqi
// * @decs TODO
// * @date 2025/7/28
// */
//@RestController
//@RequestMapping("/admin/site")
//@RequiredArgsConstructor
//@Api(tags = "后台系统-站点管理")
//public class SiteController {
//
//    private final SiteService siteService;
//    private final AreaService areaService;
//
//    @ApiOperation("新增站点")
//    @PostMapping
//    public Result createSite( @RequestBody Site site) {
//        boolean saved = siteService.save(site);
//        if (saved) {
//            return new Result(CodeConstant.SUCCESS, MessageConstant.ADD_SITE_SUCCESS);
//        }
//        return new Result(CodeConstant.FAIL, MessageConstant.ADD_SITE_FAIL);
//    }
//
//    @ApiOperation("更新站点信息")
//    @PutMapping
//    public Result updateSite( @RequestBody Site site) {
//        boolean updated = siteService.updateById(site);
//        if (updated) {
//            return new Result(CodeConstant.SUCCESS, MessageConstant.UPDATE_SITE_SUCCESS);
//        }
//        return new Result(CodeConstant.FAIL, MessageConstant.UPDATE_SITE_FAIL);
//    }
//
//    @ApiOperation("删除站点")
//    @DeleteMapping("/{id}")
//    public Result deleteSite(@PathVariable Long id) {
//        try {
//            siteService.validateSiteBeforeDelete(id);
//            boolean removed = siteService.removeById(id);
//            return removed ?
//                    new Result(CodeConstant.SUCCESS, MessageConstant.DELETE_SITE_SUCCESS) :
//                    new Result(CodeConstant.FAIL, MessageConstant.DELETE_SITE_FAIL);
//        } catch (WaterException e) {
//            return new Result(CodeConstant.FAIL, e.getMessage());
//        }
//    }
//
////    @ApiOperation("获取站点的区域树")
////    @GetMapping("/{siteId}/areas")
////    public Result getAreaTree(@PathVariable Long siteId) {
////        List<Area> areas = areaService.lambdaQuery()
////                .eq(Area::getSiteId, siteId)
////                .list();
////
////        if (!CollectionUtils.isEmpty(areas)) {
////            List<AreaTreeVO> tree = buildAreaTree(areas);
////            return new Result(CodeConstant.SUCCESS, MessageConstant.QUERY_AREA_SUCCESS, tree);
////        }
////        return new Result(CodeConstant.FAIL, MessageConstant.QUERY_AREA_FAIL);
////    }
//
//    @ApiOperation("获取站点的区域树")
//    @GetMapping("/{siteId}/areas")
//    public Result getAreaTree(@PathVariable Long siteId) {
//        List<Area> areas = areaService.lambdaQuery()
//                .eq(Area::getSiteId, siteId)
//                .list();
//
//        List<AreaTreeVO> tree = buildAreaTree(areas);
//        // 即使没有区域数据，也返回成功状态和空数组
//        return new Result(CodeConstant.SUCCESS, MessageConstant.QUERY_AREA_SUCCESS, tree);
//    }
//
//    private List<AreaTreeVO> buildAreaTree(List<Area> areas) {
//        Map<Long, AreaTreeVO> nodeMap = new HashMap<>();
//        List<AreaTreeVO> roots = new ArrayList<>();
//
//        // 创建所有节点
//        for (Area area : areas) {
//            AreaTreeVO node = new AreaTreeVO();
//            node.setId(area.getId());
//            node.setName(area.getName());
//            node.setParentAreaId(area.getParentAreaId());
//            node.setChildren(new ArrayList<>());
//            nodeMap.put(area.getId(), node);
//
//            if (area.getParentAreaId() == null || area.getParentAreaId() == 0L) {
//                roots.add(node);
//            }
//        }
//
//        // 构建层级关系
//        for (Area area : areas) {
//            if (area.getParentAreaId() != null && area.getParentAreaId() != 0L) {
//                AreaTreeVO parent = nodeMap.get(area.getParentAreaId());
//                if (parent != null) {
//                    parent.getChildren().add(nodeMap.get(area.getId()));
//                }
//            }
//        }
//
//        return roots;
//    }
//}
package com.geek.water.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.geek.water.constant.CodeConstant;
import com.geek.water.constant.MessageConstant;
import com.geek.water.entity.Area;
import com.geek.water.entity.Site;
import com.geek.water.exception.WaterException;
import com.geek.water.result.Result;
import com.geek.water.service.AreaService;
import com.geek.water.service.SiteService;
import com.geek.water.vo.AreaTreeVO;
import com.geek.water.vo.HierarchyNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yangwenqi
 * @decs TODO
 * @date 2025/7/28
 */
@RestController
@RequestMapping("/admin/site")
@RequiredArgsConstructor
@Api(tags = "后台系统-站点管理")
public class SiteController {

    private final SiteService siteService;
    private final AreaService areaService;

    @ApiOperation("获取站点分页列表")
    @PreAuthorize("hasAuthority('site:view')")
    @GetMapping("/page")
    public Result getSitePage(@RequestParam(defaultValue = "1") Integer currentPage,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(required = false) String name,
                              @RequestParam(required = false) String address) {
        try {
            // 这里需要根据您的分页查询方式来实现
            // 假设您使用MyBatis-Plus的Page对象
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<Site> page =
                    new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(currentPage, pageSize);

            // 构建查询条件
            com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Site> queryWrapper =
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();

            if (name != null && !name.trim().isEmpty()) {
                queryWrapper.like(Site::getName, name);
            }
            if (address != null && !address.trim().isEmpty()) {
                queryWrapper.like(Site::getAddress, address);
            }

            // 按创建时间倒序排列
            queryWrapper.orderByDesc(Site::getCreatedAt);

            com.baomidou.mybatisplus.extension.plugins.pagination.Page<Site> result =
                    siteService.page(page, queryWrapper);

            Map<String, Object> data = new HashMap<>();
            data.put("records", result.getRecords());
            data.put("total", result.getTotal());
            data.put("current", result.getCurrent());
            data.put("size", result.getSize());

            return new Result(CodeConstant.SUCCESS, MessageConstant.QUERY_SITE_SUCCESS, data);
        } catch (Exception e) {
            return new Result(CodeConstant.FAIL, MessageConstant.QUERY_SITE_FAIL);
        }
    }

    @ApiOperation("获取站点表单数据")
    @PreAuthorize("hasAuthority('site:view')")
    @GetMapping("/{id}/form")
    public Result getSiteFormData(@PathVariable Long id) {
        try {
            Site site = siteService.getById(id);
            if (site != null) {
                return new Result(CodeConstant.SUCCESS, MessageConstant.QUERY_SITE_SUCCESS, site);
            }
            return new Result(CodeConstant.FAIL, "站点不存在");
        } catch (Exception e) {
            return new Result(CodeConstant.FAIL, MessageConstant.QUERY_SITE_FAIL);
        }
    }

    @ApiOperation("新增站点")
    @PreAuthorize("hasAuthority('site:operate')")
    @PostMapping
    public Result createSite( @RequestBody Site site) {
        boolean saved = siteService.save(site);
        if (saved) {
            return new Result(CodeConstant.SUCCESS, MessageConstant.ADD_SITE_SUCCESS);
        }
        return new Result(CodeConstant.FAIL, MessageConstant.ADD_SITE_FAIL);
    }

    @ApiOperation("更新站点信息")
    @PreAuthorize("hasAuthority('site:operate')")
    @PutMapping
    public Result updateSite( @RequestBody Site site) {
        boolean updated = siteService.updateById(site);
        if (updated) {
            return new Result(CodeConstant.SUCCESS, MessageConstant.UPDATE_SITE_SUCCESS);
        }
        return new Result(CodeConstant.FAIL, MessageConstant.UPDATE_SITE_FAIL);
    }

    @ApiOperation("删除站点")
    @PreAuthorize("hasAuthority('site:operate')")
    @DeleteMapping("/{id}")
    public Result deleteSite(@PathVariable Long id) {
        try {
            siteService.validateSiteBeforeDelete(id);
            boolean removed = siteService.removeById(id);
            return removed ?
                    new Result(CodeConstant.SUCCESS, MessageConstant.DELETE_SITE_SUCCESS) :
                    new Result(CodeConstant.FAIL, MessageConstant.DELETE_SITE_FAIL);
        } catch (WaterException e) {
            return new Result(CodeConstant.FAIL, e.getMessage());
        }
    }

//    @ApiOperation("获取站点的区域树")
//    @GetMapping("/{siteId}/areas")
//    public Result getAreaTree(@PathVariable Long siteId) {
//        List<Area> areas = areaService.lambdaQuery()
//                .eq(Area::getSiteId, siteId)
//                .list();
//
//        if (!CollectionUtils.isEmpty(areas)) {
//            List<AreaTreeVO> tree = buildAreaTree(areas);
//            return new Result(CodeConstant.SUCCESS, MessageConstant.QUERY_AREA_SUCCESS, tree);
//        }
//        return new Result(CodeConstant.FAIL, MessageConstant.QUERY_AREA_FAIL);
//    }

    @ApiOperation("获取站点的区域树")
    @PreAuthorize("hasAuthority('area:view')")
    @GetMapping("/{siteId}/areas")
    public Result getAreaTree(@PathVariable Long siteId) {
        List<Area> areas = areaService.lambdaQuery()
                .eq(Area::getSiteId, siteId)
                .list();

        List<AreaTreeVO> tree = buildAreaTree(areas);
        // 即使没有区域数据，也返回成功状态和空数组
        return new Result(CodeConstant.SUCCESS, MessageConstant.QUERY_AREA_SUCCESS, tree);
    }

    private List<AreaTreeVO> buildAreaTree(List<Area> areas) {
        Map<Long, AreaTreeVO> nodeMap = new HashMap<>();
        List<AreaTreeVO> roots = new ArrayList<>();

        // 创建所有节点
        for (Area area : areas) {
            AreaTreeVO node = new AreaTreeVO();
            node.setId(area.getId());
            node.setName(area.getName());
            node.setParentAreaId(area.getParentAreaId());
            node.setChildren(new ArrayList<>());
            nodeMap.put(area.getId(), node);

            if (area.getParentAreaId() == null || area.getParentAreaId() == 0L) {
                roots.add(node);
            }
        }

        // 构建层级关系
        for (Area area : areas) {
            if (area.getParentAreaId() != null && area.getParentAreaId() != 0L) {
                AreaTreeVO parent = nodeMap.get(area.getParentAreaId());
                if (parent != null) {
                    parent.getChildren().add(nodeMap.get(area.getId()));
                }
            }
        }

        return roots;
    }

    @ApiOperation("获取完整的层级数据（客户->站点->区域）")
    @PreAuthorize("hasAuthority('site:view')")
    @GetMapping("/hierarchy")
    public Result getFullHierarchy() {
        try {
            List<HierarchyNode> hierarchy = siteService.getFullHierarchy();
            return new Result(CodeConstant.SUCCESS, MessageConstant.QUERY_SUCCESS, hierarchy);
        } catch (Exception e) {
            return new Result(CodeConstant.FAIL, "获取层级数据失败");
        }
    }

    @ApiOperation("获取所有地图标记")
    @PreAuthorize("hasAuthority('site:view')")
    @GetMapping("/map/markers")
    public Result getMapMarkers(@RequestParam(required = false) Long customerId) {
        try {
            List<Site> sites = siteService.getMapMarkers(customerId);
            return new Result(CodeConstant.SUCCESS, "获取地图标记成功", sites);
        } catch (Exception e) {
            return new Result(CodeConstant.FAIL, "获取地图标记失败: " + e.getMessage());
        }
    }

    @ApiOperation("更新站点地图信息")
    @PreAuthorize("hasAuthority('site:operate')")
    @PutMapping("/{id}/map")
    public Result updateSiteMapInfo(@PathVariable Long id, @RequestBody Site site) {
        try {
            site.setId(id);
            boolean updated = siteService.updateById(site);
            return updated ?
                    new Result(CodeConstant.SUCCESS, "更新站点地图信息成功") :
                    new Result(CodeConstant.FAIL, "更新站点地图信息失败");
        } catch (Exception e) {
            return new Result(CodeConstant.FAIL, "更新站点地图信息失败: " + e.getMessage());
        }
    }

    @ApiOperation("批量更新站点地图位置")
    @PreAuthorize("hasAuthority('site:operate')")
    @PutMapping("/map/batch")
    public Result batchUpdateMapPositions(@RequestBody List<Site> sites) {
        try {
            boolean updated = siteService.batchUpdateMapPositions(sites);
            return updated ?
                    new Result(CodeConstant.SUCCESS, "批量更新地图位置成功") :
                    new Result(CodeConstant.FAIL, "批量更新地图位置失败");
        } catch (Exception e) {
            return new Result(CodeConstant.FAIL, "批量更新地图位置失败: " + e.getMessage());
        }
    }

    @ApiOperation("获取客户下的所有地图标记")
    @PreAuthorize("hasAuthority('site:view')")
    @GetMapping("/customer/{customerId}/markers")
    public Result getCustomerMarkers(@PathVariable Long customerId) {
        try {
            List<Site> markers = siteService.getCustomerMarkers(customerId);
            return new Result(CodeConstant.SUCCESS, "获取客户地图标记成功", markers);
        } catch (Exception e) {
            return new Result(CodeConstant.FAIL, "获取客户地图标记失败: " + e.getMessage());
        }
    }
}